<template>
  <div class="documents-page">
    <div class="card">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-upload
            ref="uploadRef"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            multiple
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传文档
            </el-button>
          </el-upload>
          <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-select
            v-model="searchForm.type"
            placeholder="文档类型"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option label="PDF" value="pdf" />
            <el-option label="Word" value="doc" />
            <el-option label="Excel" value="xls" />
            <el-option label="图片" value="image" />
            <el-option label="其他" value="other" />
          </el-select>
          <el-select
            v-model="searchForm.category"
            placeholder="文档分类"
            clearable
            style="width: 120px; margin-right: 10px"
            @change="handleSearch"
          >
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索文档名称"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="文档名称" min-width="200">
          <template #default="{ row }">
            <div class="document-name">
              <el-icon class="file-icon">
                <component :is="getFileIcon(row.type)" />
              </el-icon>
              <span @click="handlePreview(row)" class="file-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="文档类型" width="100">
          <template #default="{ row }">
            <el-tag>{{ getFileTypeText(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="uploaderName" label="上传者" width="120" />
        <el-table-column prop="caseTitle" label="关联案件" width="150" show-overflow-tooltip />
        <el-table-column prop="contractTitle" label="关联合同" width="150" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="上传时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handlePreview(row)">预览</el-button>
            <el-button type="success" size="small" @click="handleDownload(row)">下载</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 文档预览对话框 -->
    <DocumentPreview
      v-model:visible="previewVisible"
      :document="selectedDocument"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDocumentList, deleteDocument, downloadDocument, getDocumentCategories } from '@/api/document'
import { formatDate, formatFileSize, downloadFile } from '@/utils'
import { useUserStore } from '@/stores/user'
import type { Document, Pagination } from '@/types'
import DocumentPreview from './components/DocumentPreview.vue'

const userStore = useUserStore()
const loading = ref(false)
const selectedIds = ref<string[]>([])
const tableData = ref<Document[]>([])
const previewVisible = ref(false)
const selectedDocument = ref<Document | null>(null)
const categories = ref<any[]>([])

const searchForm = reactive({
  keyword: '',
  type: '',
  category: ''
})

const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0
})

// 上传配置
const uploadAction = computed(() => '/api/document/upload')
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${userStore.token}`
}))

// 获取文档列表
const fetchDocumentList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    const data = await getDocumentList(params)
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 获取文档分类
const fetchCategories = async () => {
  try {
    const data = await getDocumentCategories()
    categories.value = data
  } catch (error) {
    console.error('获取文档分类失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchDocumentList()
}

// 选择变化
const handleSelectionChange = (selection: Document[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response: any) => {
  ElMessage.success('文档上传成功')
  fetchDocumentList()
}

// 上传失败
const handleUploadError = (error: any) => {
  ElMessage.error('文档上传失败')
}

// 预览文档
const handlePreview = (row: Document) => {
  selectedDocument.value = row
  previewVisible.value = true
}

// 下载文档
const handleDownload = async (row: Document) => {
  try {
    const blob = await downloadDocument(row.id)
    downloadFile(URL.createObjectURL(blob), row.name)
  } catch (error) {
    ElMessage.error('文档下载失败')
  }
}

// 删除文档
const handleDelete = async (row: Document) => {
  try {
    await ElMessageBox.confirm(`确定要删除文档 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteDocument(row.id)
    ElMessage.success('删除成功')
    fetchDocumentList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个文档吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await Promise.all(selectedIds.value.map(id => deleteDocument(id)))
    ElMessage.success('批量删除成功')
    fetchDocumentList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchDocumentList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchDocumentList()
}

// 获取文件图标
const getFileIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    pdf: 'Document',
    doc: 'Document',
    docx: 'Document',
    xls: 'Document',
    xlsx: 'Document',
    ppt: 'Document',
    pptx: 'Document',
    txt: 'Document',
    image: 'Picture',
    jpg: 'Picture',
    jpeg: 'Picture',
    png: 'Picture',
    gif: 'Picture',
    zip: 'FolderOpened',
    rar: 'FolderOpened'
  }
  return iconMap[type.toLowerCase()] || 'Document'
}

// 获取文件类型文本
const getFileTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    pdf: 'PDF',
    doc: 'Word',
    docx: 'Word',
    xls: 'Excel',
    xlsx: 'Excel',
    ppt: 'PPT',
    pptx: 'PPT',
    txt: '文本',
    jpg: '图片',
    jpeg: '图片',
    png: '图片',
    gif: '图片',
    zip: '压缩包',
    rar: '压缩包'
  }
  return textMap[type.toLowerCase()] || type.toUpperCase()
}

onMounted(() => {
  fetchDocumentList()
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.documents-page {
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .document-name {
    display: flex;
    align-items: center;
    
    .file-icon {
      margin-right: 8px;
      color: #409eff;
    }
    
    .file-name {
      cursor: pointer;
      color: #409eff;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}
</style>
